package com.lagou.handler;

import com.lagou.module.RpcRequest;
import com.lagou.service.IUserService;
import com.lagou.service.UserServiceImpl;
import com.lagou.util.BeanGetUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.cglib.reflect.FastClass;
import org.springframework.cglib.reflect.FastMethod;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 自定义的业务处理器
 */

public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 强转
        RpcRequest rpcRequest = (RpcRequest) msg;
        Class<?> aClass = Class.forName(rpcRequest.getClassName());
        Object bean = BeanGetUtil.getBeanByType(aClass);

        // cglib动态代理
        FastClass fastClass = FastClass.create(bean.getClass());
        // 通过方法签名获取方法
        FastMethod method = fastClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object result = method.invoke(bean, rpcRequest.getParameters());
        ctx.writeAndFlush(result);
    }
}
